{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "找到，许嵩 - 摄影艺术,为您播放\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import argparse\n",
    "import random\n",
    "import subprocess\n",
    "import re\n",
    "import sys\n",
    "root_dir = \"/xiaobai/\"\n",
    "sys.path.append(root_dir)\n",
    "from xiaobai import XiaoBai,BaseSkill\n",
    "\n",
    "class MusicSkill(BaseSkill): \n",
    "    #递归找出指定文件夹下的所有mp3文件\n",
    "    def getfiles(self,dir): \n",
    "        lists = []\n",
    "        for item in os.listdir(dir): \n",
    "            path = os.path.join(dir, item) \n",
    "            if os.path.isdir(path): \n",
    "                lists.extend(self.getfiles(path))\n",
    "            elif os.path.splitext(path)[1]==\".mp3\" :\n",
    "                lists.append(path)\n",
    "        return lists\n",
    "    #根据关键字查找对应的mp3文件，如果有多个匹配项，随机返回一个\n",
    "    def find_music(self,keyword = \"\"):\n",
    "        result=[]\n",
    "        for item in self.lists:\n",
    "            if item.find(keyword) >= 0:\n",
    "                result.append(item)\n",
    "        if len(result) > 0:\n",
    "            n = random.randint(0,len(result)-1)\n",
    "            music = result[n]\n",
    "            return music\n",
    "        else:\n",
    "            return None\n",
    "    #调用系统命令播放音乐\n",
    "    @staticmethod\n",
    "    def play_music(path):\n",
    "        os.system('mpg123 \"'+ path+'\"')    \n",
    "    def __init__(self):\n",
    "        path = \"/xiaobai/resources/music\"\n",
    "        self.lists = self.getfiles(path)\n",
    "    #继承BaseSkill类，必须定义has_intent和action方法\n",
    "    def has_intent(self,text=\"\"):\n",
    "        keywords = [\"我想听\",\"播放\"] #如果说了 我想听、播放 一类的词就认为有播放音乐的意图，再由action函数判断应该播放哪一首歌曲\n",
    "        for i in keywords:\n",
    "            if text.find(i)>=0:\n",
    "                return True\n",
    "        return False\n",
    "    def action(self,text=\"\",callback=print):\n",
    "        m = re.search('(我想听|播放)(.+?)(的歌$|$)', text)\n",
    "        if m is not None:\n",
    "            search = m.groups()[1]\n",
    "            result = self.find_music(search)\n",
    "            if result is not None:\n",
    "                callback(\"找到，\"+os.path.basename(result).replace('.mp3','')+\",为您播放\")\n",
    "                self.play_music(result)\n",
    "            else:\n",
    "                callback(\"未找到\",search)\n",
    "#测试\n",
    "if __name__ == '__main__':\n",
    "    s = MusicSkill()\n",
    "    s.handle(\"我想听许嵩的歌\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Listening...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:snowboy:Keyword 1 detected at time: 2019-05-11 07:09:57\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你：播放许嵩的歌\n",
      "小白：找到，许嵩 - 有何不可,为您播放\n",
      "stop\n"
     ]
    }
   ],
   "source": [
    "keyword_model = root_dir+'resources/小白.pmdl'\n",
    "xiaobai = XiaoBai(keyword_model=keyword_model)\n",
    "xiaobai.add_skill(MusicSkill())\n",
    "xiaobai.listen_for_keyword()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
